package com.autorun.server.service;

import com.autorun.server.dto.CreateUserRequest;
import com.autorun.server.dto.LoginRequest;
import com.autorun.server.dto.UpdateUserRequest;
import com.autorun.server.entity.User;
import com.autorun.server.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务类
 * 
 * @author autorun
 * @version 1.0.0
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户登录
     * 
     * @param request 登录请求
     * @return 用户信息
     */
    public User login(LoginRequest request) {
        log.info("用户登录尝试 - 用户名: {}", request.getUsername());

        User user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            log.warn("用户不存在: {}", request.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        log.info("找到用户 - ID: {}, 用户名: {}", user.getId(), user.getUsername());

        boolean passwordMatch = passwordEncoder.matches(request.getPassword(), user.getPassword());
        log.info("密码验证结果: {}", passwordMatch);

        if (!passwordMatch) {
            log.warn("密码验证失败 - 用户: {}", request.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        log.info("登录成功 - 用户: {}", user.getUsername());
        return user;
    }

    /**
     * 根据ID获取用户
     * 
     * @param id 用户ID
     * @return 用户信息
     */
    public User getUserById(Integer id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user;
    }

    /**
     * 获取用户列表（管理员功能）
     * 
     * @return 用户列表
     */
    public List<User> getUserList() {
        return userMapper.selectList(null);
    }

    /**
     * 创建新用户（管理员功能）
     * 
     * @param request 创建用户请求
     * @return 用户信息
     */
    @Transactional
    public User createUser(CreateUserRequest request) {
        // 检查用户名是否已存在
        Integer count = userMapper.countByUsername(request.getUsername());
        if (count > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setNumber(request.getNumber());
        user.setIsAdmin(request.getIsAdmin());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        userMapper.insert(user);
        return user;
    }

    /**
     * 更新用户信息（管理员功能）
     * 
     * @param userId 用户ID
     * @param request 更新请求
     * @return 用户信息
     */
    @Transactional
    public User updateUser(Integer userId, UpdateUserRequest request) {
        // 检查用户是否存在
        User existingUser = getUserById(userId);

        // 如果用户名发生变化，检查新用户名是否已存在
        if (!request.getUsername().equals(existingUser.getUsername())) {
            Integer count = userMapper.countByUsernameExcludeId(request.getUsername(), userId);
            if (count > 0) {
                throw new RuntimeException("用户名已存在");
            }
        }

        // 更新用户信息
        existingUser.setUsername(request.getUsername());
        existingUser.setNumber(request.getNumber());
        existingUser.setIsAdmin(request.getIsAdmin());
        existingUser.setUpdateTime(LocalDateTime.now());

        userMapper.updateById(existingUser);
        return existingUser;
    }

    /**
     * 删除用户（管理员功能）
     * 
     * @param userId 用户ID
     */
    @Transactional
    public void deleteUser(Integer userId) {
        // 检查用户是否存在
        User user = getUserById(userId);
        
        // 删除用户（关联的角色会通过外键约束自动删除）
        userMapper.deleteById(userId);
        
        log.info("删除用户成功 - ID: {}, 用户名: {}", userId, user.getUsername());
    }

    /**
     * 重置用户密码（管理员功能）
     * 
     * @param userId 用户ID
     * @param newPassword 新密码
     */
    @Transactional
    public void resetUserPassword(Integer userId, String newPassword) {
        // 检查用户是否存在
        User user = getUserById(userId);

        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setUpdateTime(LocalDateTime.now());

        userMapper.updateById(user);
        
        log.info("重置密码成功 - 用户ID: {}", userId);
    }
}